package com.xydtech.ecard.merchant.controller;

import com.xydtech.common.annotation.Log;
import com.xydtech.common.core.controller.BaseController;
import com.xydtech.common.core.domain.AjaxResult;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.core.page.TableDataInfo;
import com.xydtech.common.enums.BusinessType;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.GeoUtil;
import com.xydtech.common.utils.ShiroUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.poi.ExcelUtil;
import com.xydtech.ecard.config.service.IEcardApiSysConfigService;
import com.xydtech.ecard.merchant.domain.EcardBranchMerchant;
import com.xydtech.ecard.merchant.domain.EcardYSQBranchMerchant;
import com.xydtech.ecard.merchant.domain.EcardYSQMapInfo;
import com.xydtech.ecard.merchant.service.IEcardBranchMerchantService;
import com.xydtech.ecard.merchant.service.IEcardYSQMapInfoService;
import com.xydtech.system.domain.SysConfig;
import com.xydtech.system.service.ISysConfigService;
import com.xydtech.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <dd>描述: ~ 云商圈地图Controller</dd>
 * <dd>创建时间：  14:20 2024/2/4</dd>
 * <dd>创建人： yuzhiguo</dd>
 * <dt>版本历史: </dt>
 * Date         Author         Version     Description
 * ------------------------------------------------------------------
 * 2024/2/4     yuzhiguo         1.0        1.0 Version
 */
@Controller
@RequestMapping("/ysqmap/info")
public class EcardYSQMapInfoController extends BaseController {

    private String prefix = "ecard/ysq";

    @Value("${ysp.tileIp}")
    private String tileIp;

    @Autowired
    private IEcardYSQMapInfoService ecardYSQMapInfoService;
    @Autowired
    private IEcardApiSysConfigService ecardApiSysConfigService;
    @Autowired
    private IEcardBranchMerchantService ecardBranchMerchantService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 跳转电子地图
     *
     * @author yuzhiguo
     * @date 2024/9/3 下午2:15
     */
    @GetMapping()
    public String ysqmap(ModelMap mmap)
    {
        SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(ShiroUtils.getSysUser().getDeptId());
        String configByKey = sysConfigService.selectConfigByKey("ecard_map_clusterer", dept.getDeptId());
        mmap.put("tileIp", tileIp);
        mmap.put("isClusterer", configByKey);//电子名片-电子地图是否开启聚合点，0：开启，1：关闭
        return prefix + "/ysqMapOffLine";
    }

    /**
     * 跳转电子地图个人列表
     *
     * @author yuzhiguo
     * @date 2024/9/3 下午2:16
     */
    @GetMapping("/ysqPerson/{ysqId}")
    public String ysqPerson(@PathVariable("ysqId") String ysqId, ModelMap mmap)
    {
        mmap.put("ysqId", ysqId);
        return prefix + "/ysqPerson";
    }

    /**
     * 跳转电子地图商户列表
     *
     * @author yuzhiguo
     * @date 2024/9/3 下午2:16
     */
    @GetMapping("/ysqMerchant/{ysqId}")
    public String ysqMerchant(@PathVariable("ysqId") String ysqId, ModelMap mmap)
    {
        mmap.put("ysqId", ysqId);
        return prefix + "/ysqMerchant";
    }
    /**
     * 跳转电子地图企业列表
     *
     * @author yuzhiguo
     * @date 2024/9/3 下午2:17
     */
    @GetMapping("/ysqEnterprise/{ysqId}")
    public String ysqEnterprise(@PathVariable("ysqId") String ysqId, ModelMap mmap)
    {
        mmap.put("ysqId", ysqId);
        return prefix + "/ysqEnterprise";
    }

    /**
     * 跳转电子地图农业列表
     *
     * @author yuzhiguo
     * @date 2024/9/3 下午2:17
     */
    @GetMapping("/ysqAgriculture/{ysqId}")
    public String ysqAgriculture(@PathVariable("ysqId") String ysqId, ModelMap mmap)
    {
        mmap.put("ysqId", ysqId);
        return prefix + "/ysqAgriculture";
    }

    @GetMapping("/ysqBranchMerchant/{deptId}")
    public String ysqBranchMerchant(@PathVariable("deptId") String deptId, ModelMap mmap)
    {
        mmap.put("deptId", deptId);
        return prefix + "/ysqBranchMerchant";
    }

    /**
     * 获取客户分布展示在地图上
     * @param ecardYSQMapInfo
     * @return
     */
    @PostMapping(value = "/getCustDistribution")
    @ResponseBody
    public ResponseModel getCustDistribution(EcardYSQMapInfo ecardYSQMapInfo) {
        String coordinate = ecardYSQMapInfo.getCoordinate();//传入的经纬度
        List<EcardYSQMapInfo> ecardYSQMapInfoList = ecardYSQMapInfoService.getCustDistribution(ecardYSQMapInfo);
        List<EcardYSQMapInfo> list = new ArrayList<>();
        //循环查全部的商户集合
        for (EcardYSQMapInfo ysqMapInfo : ecardYSQMapInfoList) {
            String clockInPlace[] = ysqMapInfo.getCoordinate().split(",");
            //电子名片存入经纬度是腾讯地图获取的经纬度，由于现在用的是百度地图，所以经纬度需要转换
            //腾讯经纬度转百度经纬度
            String mapTx2bd = map_tx2bd(Double.valueOf(clockInPlace[0]), Double.valueOf(clockInPlace[1]));
            if (!StringUtils.objIsNullOrEmpty(coordinate)){
                String baiduPlace[] = mapTx2bd.split(",");
                String place[] = coordinate.split(",");
                Double distance = GeoUtil.GetDistance(Double.valueOf(baiduPlace[1]), Double.valueOf(baiduPlace[0]), Double.valueOf(place[0]), Double.valueOf(place[1]));
                BigDecimal bigDistance = new BigDecimal(distance);
                BigDecimal bigValue = new BigDecimal(600);
                if (bigDistance.compareTo(bigValue) <= 0) {
                    list.add(ysqMapInfo);
                }
            }
            //替换原来的经纬度
            ysqMapInfo.setCoordinate(mapTx2bd);
        }
        if (!StringUtils.objIsNullOrEmpty(coordinate)){
            return ResponseModel.okToJSONArray(list);
        }else {
            return ResponseModel.okToJSONArray(ecardYSQMapInfoList);
        }
    }

    /**
     * 初始化默认点坐标
     * @return
     */
    @PostMapping(value = "/getDefaultPoint")
    @ResponseBody
    public ResponseModel getDefaultPoint() {
        Long deptId = getSysUser().getDeptId();
        //获取当前法人的县级机构
        SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(deptId);
        if (StringUtils.objIsNullOrEmpty(sysDept.getMapCoordinate())){
            sysDept.setMapCoordinate("35.565602,116.76986");//默认为兖州
        }
        return ResponseModel.okToJSON(sysDept);
    }

    /**
     * 查询网格划分坐标点集合
     * @return
     */
    @GetMapping(value = "/getBoundaryCoordinate")
    @ResponseBody
    public ResponseModel getBoundaryCoordinate() {
        List<SysDept> deptList = getDeptList();
        for (SysDept sysDept : deptList) {
            String mapGridCoordinate = sysDept.getMapGridCoordinate();
            if (!StringUtils.objIsNullOrEmpty(mapGridCoordinate)) {
                sysDept.setMapGridCoordinate(mapGridCoordinate.replaceAll(",0", ";").replaceAll(" ", ""));
            }
        }
        return ResponseModel.okToJSONArray(deptList);
    }

    /**
     * 获取网格名称和经纬度
     * @return
     */
    @GetMapping(value = "/getGridAndCoordinate")
    @ResponseBody
    public ResponseModel getGridAndCoordinate() {
        return ResponseModel.okToJSONArray(getDeptList());
    }

    /**
     * 获取网格建档和拜访信息
     * @return
     */
    @GetMapping(value = "/getFilingVisitCount")
    @ResponseBody
    public ResponseModel getFilingVisitCount() {
        List<SysDept> deptList = getDeptList();
        List<EcardBranchMerchant> ecardBranchMerchantList = new ArrayList<>();
        for (SysDept sysDept : deptList) {
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(sysDept.getDeptId());
            EcardBranchMerchant ecardBranchMerchant = new EcardBranchMerchant();
            ecardBranchMerchant.setDeptId(sysDept.getDeptId());
           /* List<EcardBranchMerchant> list = ecardYSQMapInfoService.selectYSQBranchMerchantInfo(ecardBranchMerchant);
            int visitSum = 0;
            int merchantNum = 0;
            for (EcardBranchMerchant branchMerchant : list) {
                merchantNum += branchMerchant.getMerchantNum();
                visitSum += branchMerchant.getVisitSum();
                branchMerchant.setMerchantNum(merchantNum);
                branchMerchant.setVisitSum(visitSum);
            }
            ecardBranchMerchant.setMerchantNum(merchantNum);//建档数
            ecardBranchMerchant.setVisitSum(visitSum);//拜访数*/
            ecardBranchMerchant.setDeptName(sysDept.getDeptName());//机构名称
            ecardBranchMerchant.setMapCoordinate(sysDept.getMapCoordinate());//电子地图中心点经纬度
            ecardBranchMerchant.setMapLogo(dept.getMapLogo());//电子地图logo（获取县级机构的logo）
            ecardBranchMerchantList.add(ecardBranchMerchant);
        }

        return ResponseModel.okToJSONArray(ecardBranchMerchantList);
    }

    /**
     * 查询网点建档信息
     * @param ecardBranchMerchant
     * @return
     */
    @PostMapping("/getBranchMerchantList")
    @ResponseBody
    public TableDataInfo getBranchMerchantList(EcardBranchMerchant ecardBranchMerchant) {
        String salt = getSalt();
        startPage();
        List<EcardYSQBranchMerchant> list = ecardBranchMerchantService.selectYSQBranchInfo(ecardBranchMerchant, salt);
        return getDataTable(list);
    }

    /**
     * 导出网点建档信息
     * @param ecardBranchMerchant
     * @return
     */
    @Log(title = "导出网点建档信息", businessType = BusinessType.EXPORT)
    @PostMapping("/exportBranchMerchantList")
    @ResponseBody
    public AjaxResult exportBranchMerchantList(EcardBranchMerchant ecardBranchMerchant)
    {
        String salt = getSalt();
        List<EcardYSQBranchMerchant> list = ecardBranchMerchantService.selectYSQBranchInfo(ecardBranchMerchant, salt);
        ExcelUtil<EcardYSQBranchMerchant> util = new ExcelUtil<EcardYSQBranchMerchant>(EcardYSQBranchMerchant.class);
        return util.exportExcel(list, "网点建档信息");
    }

    /**
     * 获取当前法人机构集合
     * @return
     */
    public List<SysDept> getDeptList(){
        Long deptId = getSysUser().getDeptId();
        //获取当前法人的县级机构
        SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(deptId);
        SysDept sysDept = new SysDept();
        sysDept.setDeptType("3");
        sysDept.setStatus("0");
        sysDept.setDeptId(dept.getDeptId());
        List<SysDept> sysDeptList = sysDeptService.selectDeptListByType(sysDept);
        return sysDeptList;
    }
    /**
     * 获取商户范围
     * @return
     */
    @GetMapping(value = "/getCommercialArea")
    @ResponseBody
    public ResponseModel getCommercialArea() {
        Long deptId = ShiroUtils.getSysUser().getDeptId();
        //查询配置的范围
        SysConfig config = new SysConfig();
        config.setConfigKey("ecard_merchant_show_distance");
        SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(deptId);
        config.setDeptId(sysDept.getDeptId());
        SysConfig sysConfig = ecardApiSysConfigService.selectConfig(config);
        return ResponseModel.okToJSON(sysConfig);
    }

    /**
     * 坐标转换，腾讯地图转换成百度地图坐标
     * @param lat 腾讯纬度
     * @param lon 腾讯经度
     * @return 返回结果：经度,纬度
     */
    public static String map_tx2bd(double lat, double lon){
        double bd_lat;
        double bd_lon;
        double x_pi=3.14159265358979324;
        double x = lon, y = lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        bd_lon = z * Math.cos(theta) + 0.0065;
        bd_lat = z * Math.sin(theta) + 0.006;
        return bd_lat+","+bd_lon;
    }

    /**
     * 坐标转换，百度地图坐标转换成腾讯地图坐标
     * @param lat  百度坐标纬度
     * @param lon  百度坐标经度
     * @return 返回结果：纬度,经度
     */
    public static String map_bd2tx(double lat, double lon){
        double tx_lat;
        double tx_lon;
        double x_pi=3.14159265358979324;
        double x = lon - 0.0065, y = lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        tx_lon = z * Math.cos(theta);
        tx_lat = z * Math.sin(theta);
        return tx_lat+","+tx_lon;
    }

    public static void main(String[] args) {

        String map_bd2tx = map_bd2tx(35.710441, 116.533085);
        System.out.println("map_bd2tx = " + map_bd2tx);
    }
}
